#include "decompression.h"

int fprintcell(FILE * fichier,cellule* cell){
    int i;
    for(i=0;i<cell->taille;i++) {
        fprintf(fichier,"%c",cell->sequence[i]);
    }
    return 1;
}



int Decompresser(char * inputFileName, char * outputFileName){

    clock_t t1, t2;
    
    t1 = clock();
    
    FILE * inputFile;
    FILE * outputFile;
    
    inputFile = open_in(inputFileName);
    outputFile = open_out(outputFileName);
   
    //Debut initalisation des variables
    int n = 9;
    Code test,tesi;
    Code i;
    Code i_bis = 0;
    cellule *bidon;
    cellule *a = initCell(100);//calloc(100,sizeof(char));
    cellule *w=initCell(100);//calloc(100,sizeof(char));
    cellule *w_bis = initCell(100);//calloc(100,sizeof(char));
    cellule *tmp = initCell(100);
    cellule *w_bis_tmp;
    cellule *bis = initCell(50);//calloc(50,sizeof(char));
   
    Initialiser();
    printf("[INFO] Initialisation du dictionnaire\n");
    
    fscanf(inputFile,"%lu",&i);
    
    bidon = CodeVersChaine(i,-1);
    
    w->sequence[0] = bidon->sequence[0];
    w->taille = 1;
    bis->sequence[0] = w->sequence[0];
    w->taille = 1;

    fprintcell(outputFile,w);

    printf("[INFO] Debut de la lecture du fichier: %s\n",inputFileName);
    
    while( i_bis != 257) {
        fscanf(inputFile,"%lu",&i_bis);
        
        if( i_bis == 256 ){
            n = n + 1;
            printf("[INFO] Taille de lecture(+1): %d bits \n",n);
        }else if( i_bis == 257){
            printf("[INFO] Fin de lecture du fichier: %s \n",inputFileName);
        
        }else{

            if (i_bis>=last_elem){
                w_bis_tmp = CodeVersChaine(i,-1);
                cellcpy(w_bis,w_bis_tmp);
                cellcat(w_bis,bis);
            }
            else {
                w_bis_tmp = CodeVersChaine(i_bis,-1);
                cellcpy(w_bis,w_bis_tmp);
            }

            if (i_bis != 257 || i_bis != 256) {
                fprintcell(outputFile,w_bis);
            }

            bis->sequence[0] = w_bis->sequence[0];
            bis->taille = 1;

            Inserer(SequenceVersCode(w->sequence,w->taille),SequenceVersCode(bis->sequence,bis->taille));
            i=i_bis;

            cellcpy(w,w_bis);
        
        }
    }
    
    fclose(outputFile);
    fclose(inputFile);
    
    t2 = clock();
    temps_decompression = (float)(t2-t1)/CLOCKS_PER_SEC;

    return NO_ERROR;
}
